// const constants = require('../../utils/constants.js');
import { URL, SER_KEY } from "../../config.js"
import { POST, GET } from "../../utils/request.js"
// 右侧每一类的 bar 的高度（固定）
const RIGHT_BAR_HEIGHT = 20;
// 右侧每个子类的高度（固定）
const RIGHT_ITEM_HEIGHT = 100;
// 左侧每个类的高度（固定）
const LEFT_ITEM_HEIGHT = 50
var app=getApp()
Page({
  data: {
    imgUrls: [
    ],
    showBox: false,
    indicatorDots: false, //  是否显示面板指示点
    autoplay: true, // 是否自动切换
    circular: true, // 是否采用衔接滑动
    current: 0, // 当前所在页面的 index
    interval: 2500, // 自动切换时间间隔
    duration: 500, // 滑动动画时长
    //是否显示下面的购物车
    HZL_isCat: 0,
    //购物车的商品
    HZL_my_cat: [],
    // 购物车的数量
    HZL_num: 0,
    total_price: 0,
    //分类的数组
    HZL_categories: [
      '菜单'
    ],
    //swiper滑动的数组
    HZL_swiper_ID: 0,
    swiperCurrent: 0,
    //模拟 数据
    // 左 => 右联动 右scroll-into-view 所需的id
    HZL_toView: null,
    // 当前左侧选择的
    HZL_currentLeftSelect: null,
    // 右侧每类数据到顶部的距离（用来与 右 => 左 联动时监听右侧滚动到顶部的距离比较）
    HZL_eachRightItemToTop: [],
    HZL_leftToTop: 0,
    choose_spec_item: {},
    styleIndex:null,
    typeIndex:null,
    //选择index
    index: null,
    parentindex: null,
    //选择口味
    spec: '',
    animationData: {},
    animationData2:{},
    animationData3: {},
    tasteShow: false,
    noticeShow:false,
    ellipsis: true,
    select_num:1,
    nums: 0,
    constants:[],
    shopData:{},
    datas:{},
    choosed:'',
    choosePrice:null,//选择规格后的价格
    choosedSpecId:'',//选中的商品规格id
    choosedLspecification:'',//选中的商品规格
    choosedLattribute:'',//选中的商品属性
    first: [],//首单立减
    firstCount:false,//首单折扣
    jian: [],//满减
    oriPrice:null,//选择的初始价格
  },
  onLoad: function (options) {
    var that = this;
    //高度大小
    wx.getSystemInfo({
      success: function(res) {
        var HZL_height = res.windowHeight - 160
        var HZL_height1 = res.windowHeight - 110
        that.setData({
          HZL_height: HZL_height,
          HZL_height1: HZL_height1
        })
      }
    });
  },
 
  getProduct(){
    let that=this
    let shopId = wx.getStorageSync('id')
    let sessionId = wx.getStorageSync('session_id')
    let url = URL.HTTP_BASE_INTRANET + SER_KEY.SER_KEY3;
    let data = {
      appId: getApp().globalData.appId,
      shopId: shopId,
      sessionId: sessionId
    };
    GET(url, data, (resData) => {
      console.log(resData)
      if (resData.data.res=='SUCCESS'){
        wx.stopPullDownRefresh()
        let data = resData.data
        let sale = data.sale
        let first=[]
        let firstCount={}
        let jian=[]
        console.log(sale)
        // sale.map(item => {item.sale_content = JSON.parse(item.sale_content)})
        // console.log(sale)
        // sale.map(item=>{
        //   item.sale_type == "SALE_FIRST_MINUS" ? first.push(item):[]
        //   item.sale_type == "SALE_FIRST_DISCOUNT" ? firstCount = item : firstCount =null
        //   item.sale_type == "SALE_MINUS"? jian.push(item) : []
        // })
        // firstCount==null?'':firstCount.sale_content=firstCount.sale_content/10
        // console.log(firstCount)
        this.setData({
          first: first,
          firstCount: firstCount,
          jian: jian,
          datas: data,
          constants: data.product,
          HZL_currentLeftSelect: 'id' + data.product[0].id,
          HZL_currentLeftSelect: data.product.length ? 'id' + data.product[0].id : '',
          HZL_eachRightItemToTop: that.HZL_getEachRightItemToTop(data.product),
          shopData: data.shop,
          imgUrls: data.banner,
        })
        
        var num = data.totalCount; //购物车商品数量
        if (num == 0) {
          wx.removeTabBarBadge({ //移除tabbar右上角的文本
            index: 1, //tabbar下标
          })
        } else {
          wx.setTabBarBadge({ //tabbar右上角添加文本
            index: 1, ////tabbar下标
            text: num + '', //显示的内容
          })
        };
      }
      
    })
  },
  onShow: function() {
    this.getProduct()
  },
  chooseStore(){
    wx.navigateTo({
      url: '../chooseStore/chooseStore',
    })
  },
  details(e){
    console.log(e.currentTarget.dataset.id)
    let shopMsg = JSON.parse(wx.getStorageSync('shopData'))
    console.log(shopMsg,shopMsg.shopName, shopMsg.shopImage)
    let id = e.currentTarget.dataset.id
    wx.navigateTo({
      url: '../product-details/product-details?id=' + id + '&shopName=' + shopMsg.shop_name + '&shopImage=' + shopMsg.shop_image,
    })
  },
  //轮播图的切换事件  
  swiperChange: function(e) {
    // console.log(e);
    this.setData({
      swiperCurrent: e.detail.current //获取当前轮播图片的下标
    })
  },
  // 点击公告栏
  moreTip(){
    let that = this
    let animal2 = wx.createAnimation({
      timingFunction: 'ease-in'
    }).translate(0, -1200).step({
      duration: 400
    })
    that.setData({
      animationData2: animal2.export(),

    })
    setTimeout(function () {
      that.setData({
        noticeShow: true
      })
      wx.hideTabBar({})
    }, 400);
  },
  // 导航
  location(){
    let that=this
    let address = that.data.shopData.shop_address
    console.log(address)
    // wx.getLocation({
    //   type: 'gcj02', //返回可以用于wx.openLocation的经纬度
    //   success: function (res) {
    //     var latitude = res.latitude
    //     var longitude = res.longitude
        wx.openLocation({
          latitude: that.data.shopData.shop_latitude,
          longitude: that.data.shopData.shop_longitude,
          name: address,
          scale: 28
        })
    //   }
    // })
  },
  // 关闭
  closeNotice(){
    let that = this
    let animal2 = wx.createAnimation({
      timingFunction: 'ease-in'
    }).translate(0, 1200).step({
      duration: 500
    })
    that.setData({
      animationData2: animal2.export(),
      noticeShow: false,
    })
    wx.showTabBar({})
    setTimeout(function () {
      that.setData({
        // show: false
      })

    }, 400);
  },
  // 选择
  choose: function(e) {
    console.log(e)
    let index = e.currentTarget.dataset.index
    this.setData({
      select_num:1,
      typeIndex: null,
      styleIndex: null,
      choosed: '',
      choosePrice: null,
      choosedSpecId: '',
      choosedLspecification: '',
    })
    let that = this
    let url = URL.HTTP_BASE_INTRANET + SER_KEY.SER_KEY4;
    let data = {
      appId: getApp().globalData.appId,
      productId: e.currentTarget.dataset.id,
      shopId: wx.getStorageSync('id')
    };
    GET(url, data, (resData) => {
      let productData = resData.data.product
      console.log(productData)
      let defaultLattributeName='';
      // if (productData.lattribute&&productData.lattribute.length){
      //   defaultLattributeName = productData.lattribute &&productData.lattribute.length?productData.lattribute[0].attrValue[0].attr_value:'';
      // }
      let price1 = productData.lspecification[0].price
      let price2 = productData.lspecification[productData.lspecification.length - 1].price
      let end=0
      if (productData.lspecification.length>1){
        price1 < price2 ? end = price1 + '-' + price2 : end = price2 + '-' + price1
      }else{
        end = price1
      }
     
      this.setData({
        choose_spec_item: productData,
        // choosed: productData.lattribute&&productData.lattribute.length? productData.lspecification[0].name + '/' + productData.lattribute[0].attrValue[0].attr_value : productData.lspecification[0].name,
        choosePrice: end,
        // choosedSpecId: productData.lspecification[0].id,
        // choosedLspecification: productData.lspecification[0].name,
        choosedLattribute: defaultLattributeName,
        
      })
    })
    let animal1 = wx.createAnimation({
      timingFunction: 'ease-in'
    }).translate(0, -1200).step({
      duration: 400
    })
    that.setData({
      animationData: animal1.export(),

    })
    setTimeout(function() {
      that.setData({
        tasteShow: true
      })
      wx.hideTabBar({})
    }, 400);
  },
  close: function() {
    let that = this
    let animal1 = wx.createAnimation({
      timingFunction: 'ease-in'
    }).translate(0, 1200).step({
      duration: 500
    })
    that.setData({
      animationData: animal1.export(),
      tasteShow:false,
    })
    wx.showTabBar({})
    setTimeout(function() {
      that.setData({
        // show: false
      })
      
    }, 400);

  },
  // 选择属性
  chooseStyle: function(e) {
    let that=this;
    let name = that.data.choosedLspecification
    that.setData({
      styleIndex: e.currentTarget.dataset.index,
      choosedLattribute: e.currentTarget.dataset.name,
      choosed: name ? name + '/' + e.currentTarget.dataset.name : e.currentTarget.dataset.name
    })
  },
  //规格
  choosetype: function (e) {
    let that=this;
    let name = that.data.choosedLattribute
    let price = e.currentTarget.dataset.price
    console.log(price, that.data.select_num)
    that.setData({
      typeIndex: e.currentTarget.dataset.index,
      choosed: name ? e.currentTarget.dataset.name + '/' + name : e.currentTarget.dataset.name,
      choosePrice: (price * that.data.select_num).toFixed(2),
      oriPrice: price,
      choosedSpecId: e.currentTarget.dataset.id,
      choosedLspecification: e.currentTarget.dataset.name,
    })
  },
  // 加入购物车
  addShopCart: function() {
    let that = this;
    let shopId = wx.getStorageSync('id');
    let choosedAttrName='';
    let sessionId = wx.getStorageSync('session_id');
    let num = that.data.select_num;
    let url = URL.HTTP_BASE_INTRANET + SER_KEY.SER_KEY5;
    if (that.data.choose_spec_item.lattribute && that.data.choose_spec_item.lattribute.length){
      choosedAttrName = that.data.choosedLspecification + '-' + that.data.choosedLattribute;
    } else{
      choosedAttrName = that.data.choosedLspecification;
    }
    let data = {
      appId: getApp().globalData.appId,
      sessionId: sessionId,
      shopId: shopId,
      productId: that.data.choose_spec_item.id,
      productCount:num,
      attrName: choosedAttrName||'默认',
      specId: that.data.choosedSpecId||that.data.choose_spec_item.lspecification[0].id
    };
    console.log(data);
    if (num==0){
      wx.showToast({
        title: "购买数量不能为0",
        icon: 'none'
      })
      return;
    }
    GET(url, data, (resData) =>{
      console.log(resData);
      if (resData.data.res == "SUCCESS"){
        wx.showToast({
          title: '加入购物车成功！',
        })
        setTimeout(function () {
          that.getProduct()
          let animal1 = wx.createAnimation({
            timingFunction: 'ease-in'
          }).translate(0, 1200).step({
            duration: 500
          })
          that.setData({
            animationData: animal1.export(),
            tasteShow: false,
          })
          wx.showTabBar({})
        }, 1000);
        
      }else{
        wx.showToast({
          title: resData.data.errMsg,
          icon:'none'
        })
        setTimeout(function () {
          if(resData.data.errMsg=='登录过期'){
            wx.navigateTo({
              url: '/pages/authorized-login/authorized-login',
            })
          }
         }, 1000)
        
      }
     
    })

  },
  //立即购买
  buy(){
    let that=this
    let url = URL.HTTP_BASE_INTRANET + SER_KEY.SER_KEY18;
    let choosedAttrName = '';
    let sessionId = wx.getStorageSync('session_id');
    let shopId = wx.getStorageSync('id');
    let num = that.data.select_num;
    if (that.data.choose_spec_item.lattribute && that.data.choose_spec_item.lattribute.length) {
      choosedAttrName = that.data.choosedLspecification + '-' + that.data.choosedLattribute;
    } else {
      choosedAttrName = that.data.choosedLspecification;
    }
    let data = {
      appId: getApp().globalData.appId,
      sessionId: sessionId,
      shopId: shopId,
      productId: that.data.choose_spec_item.id,
      productCount: num,
      attrName: choosedAttrName||'默认',
      specId: that.data.choosedSpecId||that.data.choose_spec_item.lspecification[0].id
    };
    GET(url, data, (resData) => {
      console.log(resData);
      if (resData.data.res == "SUCCESS") {
        wx.navigateTo({
          url: '../order-pay/order-pay',
        })
      }else{
        wx.showToast({
          title: resData.data.errMsg,
          icon:'none'
        })
        setTimeout(function () {
          if (resData.data.errMsg == '登录过期') {
            wx.navigateTo({
              url: '/pages/authorized-login/authorized-login',
            })
          }
        }, 1000)
      }

    })
  },
  //记录swiper滚动的
  HZL_swiperchange: function(e) {
    var that = this;
    that.setData({
      HZL_swiper_ID: e.detail.current,
    })
  },
  //点击分类栏
  HZL_categories: function(e) {
    var that = this;
    that.setData({
      HZL_swiper_ID: e.currentTarget.dataset.index
    })
  },

  // 获取每个右侧的 bar 到顶部的距离，用来做后面的计算。
  HZL_getEachRightItemToTop: function(data) {
    var obj = {};
    var totop = 0;
    var constants = data
    // 右侧第一类肯定是到顶部的距离为 0
    obj[constants[0].id] = totop 
    // 循环来计算每个子类到顶部的高度
    for (let i = 1; i < (constants.length + 1); i++) {
      totop += (RIGHT_BAR_HEIGHT + constants[i - 1].product.length * RIGHT_ITEM_HEIGHT)
      // 这个的目的是 例如有两类，最后需要 0-1 1-2 2-3 的数据，所以需要一个不存在的 'last' 项，此项即为第一类加上第二类的高度。
      obj[constants[i] ? constants[i].id : 'last'] = totop
    }
    return obj
  },
  // 监听右侧的滚动事件与 HZL_eachRightItemToTop 的循环作对比 从而判断当前可视区域为第几类，从而渲染左侧的对应类。
  right: function(e) {
    for (let i = 0; i < this.data.constants.length; i++) {
      let left = this.data.HZL_eachRightItemToTop[this.data.constants[i].id]
      let right = this.data.HZL_eachRightItemToTop[this.data.constants[i + 1] ? this.data.constants[i + 1].id : 'last']
      if (e.detail.scrollTop < right && e.detail.scrollTop >= left) {
        this.setData({
          HZL_currentLeftSelect: 'id'+this.data.constants[i].id,
          HZL_leftToTop: LEFT_ITEM_HEIGHT * i
        })
      }
    }
  },
  // 左侧类的点击事件，点击时，右侧会滚动到对应分类
  left: function(e) {
    console.log(e)
    this.setData({
      HZL_toView: 'id'+e.currentTarget.dataset.id ,
      HZL_currentLeftSelect: 'id'+e.currentTarget.dataset.id 
    })
  },


  //关闭
  HZL_isCat_close: function(e) {
    this.setData({
      HZL_isCat: 0
    })
  },

  // 增加
  HZL_jia: function(e) {
    console.log(e);
    let price=this.data.oriPrice
    if(price==null){
      wx.showToast({
        title: '请选择规格',
        icon:'none'
      })
      return;
    }
    let num = this.data.select_num
    num++
    this.setData({
      select_num: num,
      choosePrice: (price * num).toFixed(2)
    })
  },
  onPullDownRefresh: function () {
    this.getProduct()
  },
  //减少
  HZL_jian: function(e) {
    console.log(e);
    let num = this.data.select_num
    if (this.data.select_num > 1) {
      num--
      // console.log(this.data.oriPrice)
      this.setData({
        select_num: num,
        choosePrice: (this.data.oriPrice * num).toFixed(2)
      })
    } else {
      wx.showToast({
        title: '不能再少了！',
        icon: 'none'
      });
    }

    
  },






})